package cn.buhler.thread;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class QueryThreadPoolExecutor {

    private final ThreadPoolExecutor executor;

    public QueryThreadPoolExecutor() {
        ThreadFactory queryThreadFactory = new DefaultThreadFactory("QueryThreadFactory");
        executor = new ThreadPoolExecutor(
                5, 20, 60L, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(1000),
                queryThreadFactory,
                new ThreadPoolExecutor.AbortPolicy()
        );
    }

    public void submit(Runnable task) {
        executor.submit(task);
    }

    public void shutdown() {
        if (executor != null) {
            executor.shutdown();
            try {
                if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
                    executor.shutdownNow();
                }
            } catch (InterruptedException e) {
                executor.shutdownNow();
                Thread.currentThread().interrupt();
            }
        }
    }
}
